package mebp.genetic.recombination;

import java.util.Vector;

import mebp.genetic.Individuum;

public class TwoPointCrossover implements RecombinationStrategy {

	@Override
	public Vector<Individuum> recombine(Individuum... parents) {
		Individuum i1 = parents[0];
		Individuum i2 = parents[1];
		int genomLength = i2.genom.length;

		int child1[] = new int[genomLength];
		int child2[] = new int[genomLength];

		//double[] randomNr = generateSortedRandomNumbers(genomLength);
		Integer splitAt1 = null;
		Integer splitAt2 = null;

		double dsplitAt1 = Math.random() * genomLength;
		double dsplitAt2 = Math.random() * genomLength;
		if (dsplitAt1>dsplitAt2) {
			splitAt1 = (int)Math.floor(dsplitAt2);
			//if (splitAt1==0) splitAt1++;
			splitAt2 = (int)Math.ceil(dsplitAt1);
			//if (splitAt2==genomLength) splitAt2--;
		} else {
			splitAt1 = (int)Math.floor(dsplitAt1);
			//if (splitAt1==0) splitAt1++;
			splitAt2 = (int)Math.ceil(dsplitAt2);
			//if (splitAt2==genomLength) splitAt2--;
		}
		//System.out.println(splitAt1);
		//System.out.println(splitAt2);
		
	    System.arraycopy( i1.genom, 0, child1, 0, splitAt1);	
	    System.arraycopy( i2.genom, splitAt1, child1, splitAt1, splitAt2-splitAt1);	
	    System.arraycopy( i1.genom, splitAt2, child1, splitAt2, genomLength-splitAt2);	

	    System.arraycopy( i2.genom, 0, child2, 0, splitAt1);
	    System.arraycopy( i1.genom, splitAt1, child2, splitAt1, splitAt2-splitAt1);
	    System.arraycopy( i2.genom, splitAt2, child2, splitAt2, genomLength-splitAt2);
	    /*
		for (int j = splitAt1; j < splitAt2; j++) {
			child1[j] = child2[j];
			child2[j] = i1.genom[j];
		}*/

		Vector<Individuum> result = new Vector<Individuum>();
		
		Individuum ind1=new Individuum(i1.problem, child1);
		ind1.repair();
		if (i1.isSpanningTree()) 
		result.add(ind1);
		Individuum ind2=new Individuum(i1.problem, child2);
		ind2.repair();
		if (ind2.isSpanningTree()) 
		result.add(ind2);
		
		return result;
	}

	@Deprecated
	private double[] generateSortedRandomNumbers(int genomLength) {
		double[] result = new double[2];
		for (int i = 0; i < 2; i++) {
			double random;
			while (true) {
				random = Math.random() * genomLength;
				if (random > genomLength - 1)
					continue;
				if (random < 1)
					continue;
				break;
			}
			result[i] = random;
		}
		java.util.Arrays.sort(result);
		return result;
	}
}
